import type {MenuOption} from "naive-ui"
import {RouteRecordRaw, RouterLink} from 'vue-router'

import {h} from 'vue'
import {deepCleanOptions} from "@/utils/ArrayUtils";
import GgIcon from "@/components/icon/gg-icon.vue";


let ROUTE_TYPE = 2;
let MENU_TYPE = 1;
let HREF_TYPE = 3;

export function renderIcon(icon: string) {

  return () => h(
    GgIcon,
    {
      name: icon,
    },
  )
}

//转化为菜单数据
export function convertToMenuOption(item: Menu.MenuModel): MenuOption {
  // 统一在函数开始定义 option
  const option: MenuOption = {
    key: item.name,
    lable: item.title,
    icon: renderIcon(item.icon),
    disabled: item.disabled,
    props: {
      ...item.prop
    }
  };
  // 如果 item 具有 route 属性，设置 label 为 RouterLink
  if (item.menuType == ROUTE_TYPE) {
    //路由
    option.label = () =>
      h(
        RouterLink,
        {
          to: {path: item.route.path}
        },
        {default: () => item.title}
      );
  } else if (item.menuType == MENU_TYPE) {
    //菜单
    option.label = item.title
  } else if (item.menuType == HREF_TYPE) {
    //超链接
    option.label = () =>
      h(
        'a',
        {
          href: item.href
        },
        item.title
      );
  }

  // 如果 item 有子菜单，递归调用
  if (item.children) {
    if (Array.isArray(item.children) && item.children.length === 0) {
      delete option.children
    } else {
      option.children = deepCleanOptions(item.children.map(convertToMenuOption));
    }
  }

  // 返回最终的 option
  return option;
}


// 根据当前路由生成面包屑
export function generateBreadcrumb(menuItems: Menu.MenuModel[], currentKey: string | null): Menu.MenuModel[] {
  const result: Menu.MenuModel[] = []

  function findPath(items: Menu.MenuModel[], target: string, path: Menu.MenuModel[] = []): boolean {
    for (const item of items) {
      path.push(item)
      if (item.name === target) {
        result.push(...path)
        return true
      }
      if (item.children && findPath(item.children, target, path)) {
        return true
      }
      path.pop()
    }
    return false
  }

  if (currentKey) {
    findPath(menuItems, currentKey)
  }

  return result
}
